package com.huishu.goods.execl;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.huishu.commons.exception.NotFoundException;
import com.huishu.commons.utlis.BeanUtils;
import com.huishu.goods.pojo.model.PortfolioProductsDO;
import com.huishu.goods.pojo.model.ProductDO;
import com.huishu.goods.service.PortfolioProductsService;
import com.huishu.goods.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @ClassName：ProductDataListener
 * @Author: ljj
 * @Date: 2022/5/11 9:24
 */
@Slf4j
public class PorfolioProductDataListener implements ReadListener<PorfolioProductExecl> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000000;

    private List<PorfolioProductExecl> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private ProductService productService;

    private PortfolioProductsService portfolioProductsService;

    public PorfolioProductDataListener(ProductService productService, PortfolioProductsService portfolioProductsService) {
        // 这里是demo，所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数
        this.productService = productService;
        this.portfolioProductsService = portfolioProductsService;
    }


    @Override
    public void invoke(PorfolioProductExecl data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        Optional.ofNullable(data).ifPresent(this::checkParam);
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
       // log.info("{}条数据，开始存储数据库！", cachedDataList.size());
       // List<ProductDO> products = new ArrayList<>();
       // List<PortfolioProductsDO> portfolioProducts = new ArrayList<>();
       // Map<String, List<PorfolioProductExecl>> collect = cachedDataList.stream().collect(Collectors.groupingBy(PorfolioProductExecl::getSkuCode));
       // collect.forEach((k, v) -> {
       //     ProductDO productDO = new ProductDO();
       //     productDO.setSkuCode(k);
       //     productDO.setName(v.get(0).getName());
       //     productDO.setPrice(v.get(0).getPrice());
       //     productDO.setRetailPrice(v.get(0).getPrice());
       //     products.add(productDO);
       //     List<PortfolioProductsDO> portfolioProductsDOS = v.stream().map(porfolioProductExecl -> {
       //         PortfolioProductsDO portfolioProductsDO = new PortfolioProductsDO();
       //         portfolioProductsDO.setProductSku(k);
       //         portfolioProductsDO.setContain(porfolioProductExecl.getContain());
       //         portfolioProductsDO.setSonSku(porfolioProductExecl.getSonSku());
       //         portfolioProductsDO.setSonName(porfolioProductExecl.getSonName());
       //         portfolioProductsDO.setSonNum(porfolioProductExecl.getSonNum());
       //         return portfolioProductsDO;
       //     }).collect(Collectors.toList());
       //     portfolioProducts.addAll(portfolioProductsDOS);
       // });
       // productService.saveBatch(products);
       // portfolioProductsService.saveBatch(portfolioProducts);
       // log.info("存储数据库成功！");
       // // 存储完成清理 list
       // cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    }

    /**
     * 判断数据
     *
     * @param productExecl
     */
    public void checkParam(PorfolioProductExecl productExecl) {
        if (StringUtils.isEmpty(productExecl.getSkuCode())) {
            throw new NotFoundException("skuCode不存在");
        }
        if (StringUtils.isEmpty(productExecl.getName())) {
            throw new NotFoundException("商品名称不存在");
        }
        if (productExecl.getPrice() == null) {
            throw new NotFoundException("商品价格不存在");
        }
        if (productExecl.getSonSku() == null) {
            throw new NotFoundException("子sku不存在");
        }
        if (productExecl.getSonNum() == null) {
            throw new NotFoundException("子num不存在");
        }
    }
}
